package hk.linkcredit.walletservice.wallet.service.strategy;

import hk.linkcredit.walletservice.constant.Status;
import hk.linkcredit.walletservice.constant.WalletConstants;
import hk.linkcredit.walletservice.exception.BizException;
import hk.linkcredit.walletservice.utils.StringUtils;
import hk.linkcredit.walletservice.wallet.domain.entity.WalletOrder;
import hk.linkcredit.walletservice.wallet.domain.vo.WalletOrderReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: Jamnsin
 * @Date: 2022/6/12 16:26
 */
@Slf4j
@Component(WalletConstants.WALLET_ORDER_STATUS_2)
public class OrderPendingStrategy extends OrderStatusService implements OrderStatusStrategy {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dealWalletOrder(WalletOrderReq walletOrderReq) {
        log.info("开始处理钱包订单状态 >>> orderStatus = {}, walletOrderReq = {}", WalletConstants.WALLET_ORDER_STATUS_PENDING, walletOrderReq);

        WalletOrder walletOrder = this.getWalletOrder(walletOrderReq.getCustNo(), walletOrderReq.getOrderSerialNo());

        String orderStatus = walletOrder.getOrderStatus();
        log.info("当前订单状态：currentStatus = {}，targetStatus = {}", orderStatus, WalletConstants.WALLET_ORDER_STATUS_PENDING);
        if (checkOrderStatus(walletOrderReq.getWalletType(), orderStatus)) {
            throw new BizException(Status.WALLET_ORDER_STATUS_EXPIRED);
        }

        this.updateWalletOrder(walletOrder.getId(), WalletConstants.WALLET_ORDER_STATUS_PENDING, null);

        log.info("结束处理钱包订单状态 >>>");
    }

    private boolean checkOrderStatus(String walletType, String orderStatus) {
        return !StringUtils.equalsAny(orderStatus, WalletConstants.WALLET_ORDER_STATUS_UNDER_REVIEW, WalletConstants.WALLET_ORDER_STATUS_APPROVED);
    }

}
